package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.service.OrganizationService;
import com.juzhencms.apps.busi.service.RoleService;
import com.juzhencms.apps.busi.service.UserService;
import com.juzhencms.apps.common.interceptor.UserInterceptor;

import lombok.extern.slf4j.Slf4j;

import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

import java.util.Arrays;

@Controller
@RequestMapping("/role")
@Slf4j
public class RoleController extends BaseController {
	
	@Autowired
	private RoleService roleService;

	@Autowired
	private OrganizationService organizationService;

	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="  is_sys=0 and del_flag=0 ";
		
		where+=" and org_id in("+this.getLoginUser().getSubOrgIds()+") ";
		
		
		
		//机构筛选条件
		if( StringUtil.isNotNullOrEmpty(request.getParameter("org_id")) && !request.getParameter("org_id").equals("0")){
			/*where+=" and find_in_set(org_id,?) ";
			int org_id = new Integer(request.getParameter("org_id").toString());
			String getOrgIds = organizationService.getOrgIds(org_id);
			whereParamList.add(getOrgIds);*/
			
			
			//查询单个机构即可，不需要查询下级机构
			where+=" and org_id=? ";
			whereParamList.add(request.getParameter("org_id"));
			
		}
		
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			//请求乱码
			String name=request.getParameter("name");
			whereParamList.add("%"+name+"%");
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		if(request.getParameter("create_time_from")!=null && !request.getParameter("create_time_from").toString().trim().equals("")){
			where+=" and create_time >= ? ";
			whereParamList.add(request.getParameter("create_time_from"));
		}
		
		if(request.getParameter("create_time_to")!=null && !request.getParameter("create_time_to").toString().trim().equals("")){
			where+=" and create_time <= ? ";
			whereParamList.add(request.getParameter("create_time_to"));
		}
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
//		int start=0;
//		if(pageIndex>1){
//			start=(pageIndex-1)*pageSize;
//		}
//		whereParamList.add(start);
//		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="create_time";
		String sortOrder="desc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据			where+" and del_flag = 0 "+
//		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.role+" "+where+ " order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		String orderby = " order by "+sortField+" "+sortOrder+",id desc ";
		List dataList = roleService.getLists("", where, whereParamList, orderby, pageIndex, pageSize,0);
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
				
			}
		}
		
		//查询总条数
//		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.role+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		Map countRow = roleService.getDetail(" count(id) as count_num ", where, whereParamList.subList(0, whereParamList.size()-2), "",0);
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		return WebUtil.resultString(data,request);
	}
	
	//除角色模块外调用角色列表数据，主要是用户模块表单中使用
	@RequestMapping(value="/listData/{orgId}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String listData(@PathVariable("orgId") String orgId,HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="  publish=1 and del_flag=0 ";
		
		if(orgId!=null && !orgId.equals("")){
			where+=" and org_id = ? ";
			whereParamList.add(orgId);
		}
		
		
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			//请求乱码
			String name=request.getParameter("name");
			String nName = null;
			try {
				nName = new String(name.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			whereParamList.add("%"+nName+"%");
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		if(request.getParameter("create_time_from")!=null && !request.getParameter("create_time_from").toString().trim().equals("")){
			where+=" and create_time >= ? ";
			whereParamList.add(request.getParameter("create_time_from"));
		}
		
		if(request.getParameter("create_time_to")!=null && !request.getParameter("create_time_to").toString().trim().equals("")){
			where+=" and create_time <= ? ";
			whereParamList.add(request.getParameter("create_time_to"));
		}
		
		//排序参数 
		String sortField="position";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据	
//		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.role+" "+where+ " order by "+sortField+" "+sortOrder, whereParamList.toArray());
		
		String getLoginUserOrgIds = this.getLoginUser().getSubOrgIds();  
		String editUserRoleIds = "";
		/*//获得当前被编辑的用户的角色ID集
		if(  uid!=null  &&  !"".equals(uid) &&  !"0".equals(uid)  ) {
			int setUid = new Integer(uid);
			Map getUserDetail = userService.getDetail(setUid, "role");
			if(getUserDetail!=null && StringUtil.isNotNullOrEmpty(getUserDetail.get("role"))) {
				String roleRegex = "^,*|,*$";
				editUserRoleIds = getUserDetail.get("role").toString().replaceAll(roleRegex, "");
			}
		}*/
		
		/*//非超级管理员登录限制
		if( this.getLoginUser().getPermissions().get("root")==null && !getLoginUserOrgIds.equals("")  ) {
			//编辑用户时,将当前被编辑的用户的角色ID集&&当前登录用户的机构权限作为角色列表的限制条件
			if(  uid!=null  &&  !"".equals(uid) &&  !"0".equals(uid)  ) {
				if(!editUserRoleIds.equals("")) {
					where += " and ( find_in_set(id,?) or org_id in ("+getLoginUserOrgIds+")   ) ";
					whereParamList.add(editUserRoleIds);
				} else {
					where += " and 1=2 ";
				}
			//新增用户时，加机构权限
			} else {
				where += " and  org_id in ("+getLoginUserOrgIds+") ";
			}
		}*/
		
		String orderby = " order by "+sortField+" "+sortOrder+",id asc ";
		List dataList = roleService.getLists("", where, whereParamList, orderby, 0, 0,1);
		if(dataList!=null && dataList.size() > 0 ) {
			
			//设置编辑用户的角色选中
			String[] editUserRoleIdsArr = null;
			if(!editUserRoleIds.equals("")) {
				editUserRoleIdsArr = editUserRoleIds.split(",");
			}
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				//当前登录用户没有该角色的机构权限判断，将没有权限的置灰禁止修改
				int org_id =  new Integer(row.get("org_id").toString());
				row.put("chkDisabled",false);
				if(!organizationService.isAuth(org_id)) {
					row.put("chkDisabled",true);
				}
				//设置编辑用户的角色选中
				row.put("checked",false);
				if(editUserRoleIdsArr!=null){
					for(int j=0;j<editUserRoleIdsArr.length;j++) {
						if(row.get("id").toString().equals(editUserRoleIdsArr[j])){
							row.put("checked",true);
						}
					}
				}
			}
		}
		
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		
		String[] roleSelectedArr={};
		if(!id.equals("") && !id.equals("0")){
			Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.role+" where id=?",new Object[]{id});	
			/*String where = " del_flag=0 and id = ? ";	
			List whereParamList = new ArrayList();
			whereParamList.add(new Integer(id));
			Map record = roleService.getDetail("  *  ", where, whereParamList, "",1);	*/	
			//
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = (Date)record.get("create_time");
			record.put("create_time",sdf.format(date));
			data.put("data", record);
			
			if(record.get("permission")!=null)
				roleSelectedArr=record.get("permission").toString().split(",");
			
		}
		
		Map<String, Map> roleEditPermissionData=roleService.getRoleEditPermissionData(Arrays.asList(roleSelectedArr));
		//LogTool.print(roleEditPermissionData, Map.class);
		
		log.info(JSON.toJSONString(roleEditPermissionData));
		
		List roleEditPermissionDataList=new ArrayList(roleEditPermissionData.values());
		
		
		/*List roleEditPermissionDataList=new ArrayList();
		for (Map.Entry<String, Map> entry : roleEditPermissionData.entrySet()) {  
			roleEditPermissionDataList.add(entry.getValue());  
		} */
		
		
		//返回权限数组
		data.put("permission", roleEditPermissionDataList);
		
		//LogTool.print(roleEditPermissionDataList, this.getClass());
		
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		
		
		//System.out.println(request.getParameter("data"));
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		String name =(String) data.get("name");
		
		//机构org_id
		if(StringUtil.isNullOrEmpty(data.get("org_id"))) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "保存失败，请选择机构");
			return WebUtil.resultString(result,request);
		} else {
			int org_id = new Integer(data.get("org_id").toString());
			if(org_id <=0) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "保存失败，请选择所属机构");
				return WebUtil.resultString(result,request);
			}
			data.put("org_id",org_id );
			//机构名称  
			Map getOrg = this.getCommonService().getJdbcDao().queryRow("select name from "+DBTable.organization+" where id=? ",new Object[]{org_id});
			String org_name = "";
			if(getOrg!=null && !getOrg.get("name").equals("") ) {
				org_name = getOrg.get("name").toString();
			}
			data.put("org_name",org_name);	
		}
		
		if(id==null || id.equals("")){
			
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = new Date();
				data.put("create_time", sdf.format(date));
			}
			Map role = this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.role+" where name=? and del_flag = 0  and publish=1 limit 0,1",new Object[]{name});
			if(role!=null){
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "角色名称已存在，请重新输入");
				return WebUtil.resultString(result,request);
			}
			this.getCommonService().getJdbcDao().addObj(DBTable.role, data);
		}else{
			Map role = this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.role+" where name=? and id !=? and del_flag = 0 and publish=1 limit 0,1",new Object[]{name,id});
			if(role!=null){
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "角色名称已存在，请重新输入");
				return WebUtil.resultString(result,request);
			}
			
			//更新时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			data.put("update_time", sdf.format(date));
			this.getCommonService().getJdbcDao().updateObj(DBTable.role, data, "id");
		}
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){

		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }       
			this.getCommonService().getJdbcDao().updateSql("update "+DBTable.role+" set del_flag=1 where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.role+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	//更新发布状态
	@RequestMapping(value="/updatePublish",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePublish(HttpServletRequest request){
		String num = "1".equals(request.getParameter("publish"))?"0":"1";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.role+" set publish=? where id=?",new Object[]{num,request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	
	public static void main(String[] args){
		
		
	}
}
